package com.atguigu.mvc.controller.handler;

import com.atguigu.mvc.controller.Service.EmpService;
import com.atguigu.mvc.entity.Department;
import com.atguigu.mvc.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @author : zzf
 * @version : 1.0
 * @date : 2021/1/10
 */

@Controller
@RequestMapping("emp")
public class EmpHandler {
    @Autowired
    private EmpService empService;

    @RequestMapping("list")
    public String showList(Model model) {
        List<Employee> list = empService.getEmpList();
        model.addAttribute("list",list);
        return "target";
    }

    @RequestMapping(value = "{empId}",method = RequestMethod.DELETE)
    public String delEmp(@PathVariable("empId") String empId) {
        empService.delEmp(empId);
        return "redirect:list";
    }

    @RequestMapping(value = "{empId}",method = RequestMethod.GET)
    public String toEditPage(@PathVariable("empId") String empId,Model model) {
        Employee employee = empService.getEmp(empId);

        List<Department> deptList = empService.getDeptList();

        model.addAttribute("employee", employee);
        model.addAttribute("deptList", deptList);

        return "edit";
    }

    @RequestMapping(value = "updateEmp",method = RequestMethod.PUT)
    public String updateEmp(Employee employee) {
        empService.updateEmp(employee);
        return "redirect:/emp/list";
    }

    @RequestMapping("add")
    public String addEmp(Model model) {
        List<Department> deptList = empService.getDeptList();
        model.addAttribute("deptList",deptList);
        return "add";
    }

    @RequestMapping(value = "",method = RequestMethod.POST)
    public String saveEmp(Employee employee) {
        empService.addEmp(employee);
        return "redirect:/emp/list";
    }
}
